<template>
	<div class="batch-job-assignment-dialog">
		<!-- 顶部操作按钮 -->
		<div class="dialog-header">
			<el-button @click="handleCancel" :disabled="isProcessing || isLoadingUsers || isLoadingDepts || isLoadingJobs">取消</el-button>
			<div class="header-actions">
				<el-button v-if="currentStep > 0" @click="previousStep" :disabled="isProcessing || isLoadingUsers || isLoadingDepts || isLoadingJobs"
					>上一步</el-button
				>
				<el-button
					v-if="currentStep < 2"
					type="primary"
					@click="nextStep"
					:disabled="!canProceedToNextStep || isLoadingUsers || isLoadingDepts || isLoadingJobs"
				>
					下一步
				</el-button>
				<el-button v-if="currentStep === 2" type="primary" @click="handleConfirmAssignment" :loading="isProcessing" :disabled="!canConfirmAssignment">
					{{ isProcessing ? '分配中...' : '确认分配' }}
				</el-button>
			</div>
		</div>

		<!-- 步骤指示器 -->
		<el-steps :active="currentStep" align-center class="mb15">
			<el-step title="选择员工">
				<template #icon>
					<el-icon><User /></el-icon>
				</template>
			</el-step>
			<el-step title="选择岗位">
				<template #icon>
					<el-icon><Briefcase /></el-icon>
				</template>
			</el-step>
			<el-step title="确认分配">
				<template #icon>
					<el-icon><Check /></el-icon>
				</template>
			</el-step>
		</el-steps>

		<!-- 步骤内容 -->
		<div class="step-content">
			<!-- 步骤1：选择员工 -->
			<div v-show="currentStep === 0" class="step-panel">
				<div class="panel-header">
					<h4>选择需要分配岗位的员工</h4>
					<div class="header-actions">
						<el-button type="danger" @click="handleSelectAllUsers" :disabled="isLoadingUsers || selectedUsers.length === 0"> 清空选择 </el-button>
						<span class="selected-count">已选择: {{ selectedUsers.length }} 人</span>
					</div>
				</div>

				<!-- 预选用户提示 -->
				<div v-if="props.wtmdata?.selectedUsers && props.wtmdata.selectedUsers.length > 0" class="mb15">
					<el-alert type="info" :closable="false">
						<template #title>
							<strong>已从岗位分配明细中预选了 {{ props.wtmdata.selectedUsers.length }} 名员工</strong>
						</template>
						您可以继续选择其他员工，或者取消选择已选用户。
					</el-alert>
				</div>

				<div class="user-selection-area" v-loading="isLoadingUsers" element-loading-text="正在加载用户列表...">
					<div class="user-list">
						<el-scrollbar max-height="300px">
							<div class="user-grid">
								<div v-if="!isLoadingUsers && filteredUsers.length === 0" class="empty-state">
									<el-empty description="暂无用户数据" />
								</div>
								<div
									v-for="user in filteredUsers"
									:key="user.Value"
									:class="['user-item', { selected: isUserSelected(user.Value) }]"
									@click="toggleUserSelection(user)"
								>
									<div class="user-avatar-wrapper">
										<el-avatar
											v-if="user.Avatar && !avatarErrors[user.Value]"
											:size="32"
											:src="user.Avatar"
											class="user-avatar"
											@error="handleAvatarError(user.Value)"
										>
											<template #default>
												<div class="avatar-loading">
													<el-icon class="loading-icon">
														<Loading />
													</el-icon>
												</div>
											</template>
										</el-avatar>
										<el-avatar v-else :size="32" class="default-avatar">
											{{ getUserInitial(user) }}
										</el-avatar>
									</div>
									<div class="user-info">
										<div class="user-name">{{ getUserDisplayName(user) }}</div>
										<div class="user-detail">工号：{{ getUserDisplayCode(user) }}</div>
										<div class="user-dept">部门：{{ getUserDisplayDept(user) }}</div>
									</div>
									<el-icon v-if="isUserSelected(user.Value)" class="selected-icon">
										<Check />
									</el-icon>
								</div>
							</div>
						</el-scrollbar>
					</div>
				</div>
			</div>

			<!-- 步骤2：选择岗位 -->
			<div v-show="currentStep === 1" class="step-panel">
				<div class="panel-header">
					<h4>选择目标岗位</h4>
					<div class="selected-users-summary">
						<span>将为 {{ selectedUsers.length }} 名员工分配岗位</span>
					</div>
				</div>

				<el-alert type="info" :closable="false" class="mb15">
					<template #title>
						<strong>请依次选择公司、部门和岗位，公司和部门为必填项，岗位为可选项</strong>
					</template>
				</el-alert>

				<!-- 预填充信息提示 -->
				<div v-if="props.wtmdata?.orgId || props.wtmdata?.groupId" class="mb15">
					<el-alert type="success" :closable="false">
						<template #title>
							<strong>已根据当前申请单自动填充组织信息</strong>
						</template>
						<span v-if="props.wtmdata?.orgId">公司已预选</span>
						<span v-if="props.wtmdata?.groupId && props.wtmdata?.orgId">，部门已预选</span>
						，您可以修改或直接选择岗位。
					</el-alert>
				</div>

				<div class="job-selection-area" v-loading="isLoadingDepts || isLoadingJobs" element-loading-text="正在加载数据...">
					<el-row :gutter="20">
						<el-col :span="12">
							<WtmOrgSelector
								ref="orgSelectorRef"
								v-model="selectedOrgId"
								label="选择公司"
								prop="Entity.OrgId"
								:auth="true"
								:rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]"
								@change="handleOrgChange"
							/>
						</el-col>
						<el-col :span="24">
							<WtmDeptSelector
								ref="deptSelectorRef"
								v-model="selectedDeptId"
								:show-position="true"
								v-model:position-id="selectedJobPositionId"
								:use-row="false"
								label="选择部门"
								position-label="选择岗位"
								:clearable="true"
								:org-id="selectedOrgId"
								:auth="true"
								:rules="[{ required: true, message: '部门为必填项', trigger: 'blur' }]"
								:position-rules="[]"
								@change="handleDeptChange"
								@positionChange="handleJobPositionChange"
							/>
						</el-col>
					</el-row>

					<div v-if="selectedOrgId && selectedDeptId" class="assignment-preview">
						<h5>分配预览</h5>
						<el-card class="preview-card">
							<div class="preview-info">
								<el-row :gutter="20">
									<el-col :span="12">
										<div class="preview-item">
											<div class="preview-label">所属公司</div>
											<div class="preview-value">{{ displayOrgName }}</div>
										</div>
									</el-col>
									<el-col :span="12">
										<div class="preview-item">
											<div class="preview-label">所属部门</div>
											<div class="preview-value">{{ displayDeptName || '未知部门' }}</div>
										</div>
									</el-col>
								</el-row>
								<el-row :gutter="20">
									<el-col :span="12">
										<div class="preview-item">
											<div class="preview-label">目标岗位</div>
											<div class="preview-value">{{ displayJobPositionName || '未选择' }}</div>
										</div>
									</el-col>
									<el-col :span="12">
										<div class="preview-item">
											<div class="preview-label">分配模式</div>
											<div class="preview-value">{{ replaceCurrentJob ? '替换当前岗位' : '保留当前岗位（多岗位）' }}</div>
										</div>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">
										<div class="preview-item highlight">
											<div class="preview-label">影响员工</div>
											<div class="preview-value">{{ selectedUsers.length }} 人</div>
										</div>
									</el-col>
								</el-row>
							</div>
						</el-card>
					</div>
				</div>
			</div>

			<!-- 步骤3：确认分配 -->
			<div v-show="currentStep === 2" class="step-panel">
				<div class="panel-header">
					<h4>确认批量分配</h4>
				</div>

				<div class="confirmation-area">
					<el-alert type="warning" :closable="false" class="mb15">
						<template #title>
							<strong>请仔细确认以下信息，操作将无法撤销</strong>
						</template>
					</el-alert>

					<el-row :gutter="20">
						<el-col :span="12">
							<el-card header="分配详情">
								<div class="confirmation-detail">
									<div class="detail-item">
										<div class="detail-label">所属公司</div>
										<div class="detail-value">{{ displayOrgName }}</div>
									</div>
									<div class="detail-item">
										<div class="detail-label">所属部门</div>
										<div class="detail-value">{{ displayDeptName || '未知部门' }}</div>
									</div>
									<div class="detail-item">
										<div class="detail-label">目标岗位</div>
										<div class="detail-value">{{ displayJobPositionName || '未选择' }}</div>
									</div>
									<div class="detail-item">
										<div class="detail-label">分配模式</div>
										<div class="detail-value">{{ replaceCurrentJob ? '替换当前岗位' : '保留当前岗位（多岗位）' }}</div>
									</div>
									<div class="detail-item highlight">
										<div class="detail-label">影响员工数</div>
										<div class="detail-value">{{ selectedUsers.length }} 人</div>
									</div>
								</div>
							</el-card>
						</el-col>
						<el-col :span="12">
							<el-card header="员工清单">
								<el-scrollbar max-height="200px">
									<div class="selected-users-list">
										<div v-for="userId in selectedUsers" :key="userId" class="user-list-item">
											<el-avatar :size="24" class="mr10">
												{{ getUserName(userId)?.charAt(0) }}
											</el-avatar>
											<span>{{ getUserName(userId) }}</span>
											<span class="user-code">{{ getUserCode(userId) }}</span>
										</div>
									</div>
								</el-scrollbar>
							</el-card>
						</el-col>
					</el-row>

					<!-- 进度显示 -->
					<div v-if="isProcessing" class="processing-area">
						<el-progress :percentage="processProgress" :status="processStatus" :stroke-width="6" class="mb15" />
						<div class="processing-info">
							<p>{{ processMessage }}</p>
							<div v-if="processedResults.length > 0" class="results-summary">
								<span class="success-count">成功: {{ successCount }}</span>
								<span class="error-count">失败: {{ errorCount }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Check, Loading, User, Briefcase } from '@element-plus/icons-vue';
import other from '/@/utils/other';
import { batchOperationsApi } from '/@/api/batchOperations';

// 定义组件props
interface Props {
	/** 传入的数据 */
	wtmdata?: {
		selectedUsers?: any[]; // 预选的用户列表
		selectedUserIds?: (string | number)[]; // 预选的用户ID数组
		orgId?: string | number; // 预填充的组织ID
		groupId?: string | number; // 预填充的部门ID
		entityId?: string | number; // 来源单据ID
	};
}

const props = withDefaults(defineProps<Props>(), {
	wtmdata: () => ({}),
});

// 定义emits
const emit = defineEmits<{
	closeDrawer: [];
	closeDialog: [];
	refresh: [];
}>();

// 响应式数据
const currentStep = ref(0);
const isProcessing = ref(false);
const isLoadingUsers = ref(false);
const isLoadingDepts = ref(false);
const isLoadingJobs = ref(false);
const processProgress = ref(0);
const processStatus = ref<'success' | 'warning' | 'exception'>('success');
const processMessage = ref('');

// 用户相关数据
const allUsers = ref<any[]>([]);
const selectedUsers = ref<(string | number)[]>([]);
const avatarErrors = ref<Record<string | number, boolean>>({});

// 岗位相关数据
const selectedOrgId = ref<string | number | null>(null);
const selectedOrgName = ref<string>(''); // 存储选中的组织名称
const selectedDeptId = ref<string | number | null>(null);
const selectedDeptName = ref<string>(''); // 存储选中的部门名称
const selectedJobPositionId = ref<string | number | null>(null);
const selectedJobPositionName = ref<string>(''); // 存储选中的岗位名称
const allJobPositions = ref<any[]>([]);
const allDepts = ref<any[]>([]); // 存储部门数据

// 数据缓存
const dataCache = reactive({
	users: null as any[] | null,
	jobPositions: new Map<string, any[]>(), // 按部门ID缓存岗位数据
	lastUsersFetch: 0,
	cacheTimeout: 5 * 60 * 1000, // 5分钟缓存
});

// 分配选项
const replaceCurrentJob = ref(true);

// 处理结果
const processedResults = ref<any[]>([]);

// 组件引用
const orgSelectorRef = ref();
const deptSelectorRef = ref();

// 计算属性
const filteredUsers = computed(() => {
	// 只显示已选中的用户
	return allUsers.value.filter((user) => selectedUsers.value.includes(user.Value));
});

const canProceedToNextStep = computed(() => {
	switch (currentStep.value) {
		case 0:
			return selectedUsers.value.length > 0;
		case 1:
			// 公司、部门必填，岗位可选
			return selectedOrgId.value !== null && selectedDeptId.value !== null;
		default:
			return false;
	}
});

const canConfirmAssignment = computed(() => {
	return selectedUsers.value.length > 0 && selectedOrgId.value !== null && selectedDeptId.value !== null && !isProcessing.value;
});

const successCount = computed(() => processedResults.value.filter((r) => r.success).length);
const errorCount = computed(() => processedResults.value.filter((r) => !r.success).length);

// 计算当前显示的公司名称
const displayOrgName = computed(() => {
	const orgId = selectedOrgId.value;
	if (!orgId) return '';

	// 首先尝试使用存储的名称
	if (selectedOrgName.value) {
		return selectedOrgName.value;
	}

	// 然后尝试从组件获取
	if (orgSelectorRef.value) {
		try {
			const component = orgSelectorRef.value;
			const options = component.options || component.internalOptions || [];
			const selectedOption = options.find((option: any) => option.Value === orgId || option.value === orgId);
			if (selectedOption) {
				const name = selectedOption.Text || selectedOption.text || selectedOption.label || '';
				return name;
			}
		} catch (e) {
			// 静默处理错误
		}
	}

	return '未知公司';
});

// 计算当前显示的部门名称
const displayDeptName = computed(() => {
	const deptId = selectedDeptId.value;
	if (!deptId) return '';

	// 首先尝试使用存储的名称
	if (selectedDeptName.value) {
		return selectedDeptName.value;
	}

	// 然后尝试从组件获取
	if (deptSelectorRef.value) {
		try {
			const component = deptSelectorRef.value;
			if (component.selectedDeptText) {
				return component.selectedDeptText;
			}
		} catch (e) {
			// 静默处理错误
		}
	}

	// 最后从数据中查找
	return getDeptName(deptId);
});

// 计算当前显示的岗位名称
const displayJobPositionName = computed(() => {
	const jobPositionId = selectedJobPositionId.value;

	if (!jobPositionId) {
		return '未选择';
	}

	// 首先尝试使用存储的名称
	if (selectedJobPositionName.value) {
		return selectedJobPositionName.value;
	}

	// 然后尝试从组件获取
	if (deptSelectorRef.value) {
		try {
			const component = deptSelectorRef.value;
			if (component.selectedPositionText) {
				return component.selectedPositionText;
			}
		} catch (e) {
			// 静默处理错误
		}
	}

	// 最后从数据中查找
	return getJobPositionName(jobPositionId);
});

// 方法
const loadUsers = async () => {
	if (isLoadingUsers.value) return;

	// 检查缓存
	const now = Date.now();
	if (dataCache.users && now - dataCache.lastUsersFetch < dataCache.cacheTimeout) {
		allUsers.value = [...dataCache.users];
		return;
	}

	isLoadingUsers.value = true;
	try {
		let userData: any[] = [];
		let preselectedUserData: any[] = [];

		// 总是从API加载完整的用户列表
		userData = await other.getSelectList('/api/SysUserJobPosition/GetFrameworkUsers', [], false);

		// 如果有传入的预选用户数据，将其转换为标准格式并合并到用户列表中
		if (props.wtmdata?.selectedUsers && props.wtmdata.selectedUsers.length > 0) {
			preselectedUserData = props.wtmdata.selectedUsers.map((user) => ({
				Value: user.ID,
				Text: user.Name || '未知姓名',
				Name: user.Name || '未知姓名',
				Code: user.StaffNo || user.Code || '无工号',
				StaffNo: user.StaffNo || user.Code || '无工号',
				ITCode: user.StaffNo || user.Code || '无工号',
				DeptName: user.Group?.Name || user.GroupName || user.DeptName || '未知部门',
				GroupName: user.Group?.Name || user.GroupName || user.DeptName || '未知部门',
				Department: user.Group?.Name || user.GroupName || user.DeptName || '未知部门',
				Avatar: user.PhotoId ? `/api/_file/getfile/${user.PhotoId}` : user.Photo ? `/api/_file/getfile/${user.Photo.ID}` : null,
			}));

			// 合并预选用户数据到完整用户列表中，避免重复
			preselectedUserData.forEach((preUser) => {
				const existingUserIndex = userData.findIndex((u) => u.Value === preUser.Value || String(u.Value) === String(preUser.Value));

				if (existingUserIndex >= 0) {
					// 如果用户已存在，用预选数据更新它（因为预选数据可能更准确）
					userData[existingUserIndex] = { ...userData[existingUserIndex], ...preUser };
				} else {
					// 如果用户不存在，添加到列表中
					userData.push(preUser);
				}
			});
		}

		allUsers.value = userData;

		// 缓存数据
		dataCache.users = userData;
		dataCache.lastUsersFetch = now;
	} catch (error: any) {
		ElMessage.error(`加载用户列表失败: ${error.message || '网络错误'}`);
		// 清空数据
		allUsers.value = [];
	} finally {
		isLoadingUsers.value = false;
	}
};

// 加载部门数据
const loadDepts = async () => {
	if (isLoadingDepts.value) return;

	isLoadingDepts.value = true;
	try {
		const response = await other.getSelectList('/api/common/getgroups', [], false);
		allDepts.value = response || [];
	} catch (error) {
		ElMessage.error('加载部门数据失败');
	} finally {
		isLoadingDepts.value = false;
	}
};

// 加载岗位数据
const loadJobPositions = async (groupId?: string | number) => {
	if (isLoadingJobs.value) return;

	const cacheKey = String(groupId || 'all');

	// 检查缓存
	if (dataCache.jobPositions.has(cacheKey)) {
		allJobPositions.value = [...dataCache.jobPositions.get(cacheKey)!];
		return;
	}

	isLoadingJobs.value = true;
	try {
		// 根据是否有部门ID来构建API URL
		const url = groupId ? `/api/common/getjobpositions?groupId=${groupId}` : '/api/common/getjobpositions';
		const response = await other.getSelectList(url, [], false);
		const jobPositionsData = response || [];

		allJobPositions.value = jobPositionsData;

		// 缓存数据
		dataCache.jobPositions.set(cacheKey, jobPositionsData);
	} catch (error: any) {
		ElMessage.error(`加载岗位数据失败: ${error.message || '网络错误'}`);
		// 清空数据
		allJobPositions.value = [];
	} finally {
		isLoadingJobs.value = false;
	}
};

// 直接调用API获取组织名称
const getOrgNameFromApi = async (orgId: string | number) => {
	try {
		const response = await other.getSelectList('/api/common/getorganizations', [], false);

		if (response && response.length > 0) {
			const org = response.find((o: any) => {
				return (
					o.Value == orgId ||
					o.value == orgId ||
					o.ID == orgId ||
					o.id == orgId ||
					String(o.Value) === String(orgId) ||
					String(o.ID) === String(orgId)
				);
			});

			if (org) {
				const orgName = org.Text || org.text || org.label || org.Name || org.name || '未知公司';
				selectedOrgName.value = orgName;
				return orgName;
			} else {
				selectedOrgName.value = '未知公司';
				return '未知公司';
			}
		} else {
			selectedOrgName.value = '未知公司';
			return '未知公司';
		}
	} catch (error: any) {
		selectedOrgName.value = '未知公司';
		return '未知公司';
	}
};

// 递归查找部门（支持树形结构）
const findDeptInTree = (deptList: any[], deptId: string | number): any => {
	for (const dept of deptList) {
		// 检查当前部门
		if (dept.Value == deptId || dept.value == deptId || String(dept.Value) === String(deptId) || String(dept.value) === String(deptId)) {
			return dept;
		}

		// 递归检查子部门
		if (dept.children && dept.children.length > 0) {
			const found = findDeptInTree(dept.children, deptId);
			if (found) return found;
		}

		// 有些API可能使用 Children 字段
		if (dept.Children && dept.Children.length > 0) {
			const found = findDeptInTree(dept.Children, deptId);
			if (found) return found;
		}
	}
	return null;
};

// 直接调用API获取部门名称
const getDeptNameFromApi = async (deptId: string | number) => {
	try {
		// 需要传递组织ID参数来获取对应组织下的部门列表
		const apiUrl = selectedOrgId.value ? `/api/common/getgroups?orgId=${selectedOrgId.value}` : '/api/common/getgroups';
		const response = await other.getSelectList(apiUrl, [], false);

		if (response && response.length > 0) {
			// 使用递归查找支持树形结构的部门
			const dept = findDeptInTree(response, deptId);

			if (dept) {
				const deptName = dept.Text || dept.text || dept.label || '未知部门';
				selectedDeptName.value = deptName;
				return deptName;
			} else {
				selectedDeptName.value = '未知部门';
				return '未知部门';
			}
		} else {
			selectedDeptName.value = '未知部门';
			return '未知部门';
		}
	} catch (error) {
		selectedDeptName.value = '未知部门';
		return '未知部门';
	}
};

// 直接调用API获取岗位名称
const getPositionNameFromApi = async (positionId: string | number) => {
	try {
		// 先从已加载的岗位数据中查找
		let position = allJobPositions.value.find((p: any) => p.Value == positionId || p.value == positionId);

		if (!position && selectedDeptId.value) {
			// 如果没找到且有部门ID，重新加载该部门的岗位数据
			await loadJobPositions(selectedDeptId.value);
			position = allJobPositions.value.find((p: any) => p.Value == positionId || p.value == positionId);
		}

		if (!position) {
			// 如果还是没找到，调用通用岗位API
			const response = await other.getSelectList('/api/common/getjobpositions', [], false);
			position = response?.find((p: any) => p.Value == positionId || p.value == positionId);
		}

		const positionName = position?.Text || position?.text || position?.label || '未知岗位';
		selectedJobPositionName.value = positionName;
		return positionName;
	} catch (error) {
		selectedJobPositionName.value = '未知岗位';
		return '未知岗位';
	}
};

const isUserSelected = (userId: string | number) => {
	return selectedUsers.value.includes(userId);
};

const toggleUserSelection = (user: any) => {
	const userId = user.Value;
	const index = selectedUsers.value.indexOf(userId);

	if (index > -1) {
		selectedUsers.value.splice(index, 1);
	} else {
		selectedUsers.value.push(userId);
	}
};

const handleSelectAllUsers = () => {
	// 清空所有选中的用户
	selectedUsers.value = [];
};

const handleDeptChange = async (deptId: string | number | null, deptText?: string, ...args: any[]) => {
	selectedDeptId.value = deptId;

	if (deptId) {
		// 直接调用API获取部门名称
		await getDeptNameFromApi(deptId);
	} else {
		// 清空部门名称
		selectedDeptName.value = '';
	}

	// 清空岗位选择，因为部门变化了
	selectedJobPositionId.value = null;
	selectedJobPositionName.value = '';

	// 触发岗位重新加载（如果在选择岗位步骤）
	if (deptId && currentStep.value === 1) {
		nextTick(() => {
			loadJobPositions(deptId);
		});
	}
};

const handleJobPositionChange = async (jobPositionId: string | number | null, jobPositionText?: string, ...args: any[]) => {
	selectedJobPositionId.value = jobPositionId;

	if (jobPositionId) {
		// 直接调用API获取岗位名称
		await getPositionNameFromApi(jobPositionId);
	} else {
		// 清空岗位名称
		selectedJobPositionName.value = '';
	}
};

// 处理公司选择变化
const handleOrgChange = async (orgId: string | number | null) => {
	// 清空部门和岗位选择
	selectedDeptId.value = '';
	selectedDeptName.value = '';
	selectedJobPositionId.value = '';
	selectedJobPositionName.value = '';

	// 更新选择的公司ID
	selectedOrgId.value = orgId;

	if (orgId) {
		// 尝试从组件的options中获取公司名称
		let orgName = '';
		try {
			if (orgSelectorRef.value) {
				const component = orgSelectorRef.value;
				const options = component.options || component.internalOptions || component.data || component.items || [];

				const selectedOption = options.find(
					(option: any) =>
						option.Value === orgId ||
						option.value === orgId ||
						option.ID === orgId ||
						option.id === orgId ||
						String(option.Value) === String(orgId) ||
						String(option.value) === String(orgId) ||
						String(option.ID) === String(orgId) ||
						String(option.id) === String(orgId)
				);

				if (selectedOption) {
					orgName = selectedOption.Text || selectedOption.text || selectedOption.label || selectedOption.Name || selectedOption.name || '';
				}
			}
		} catch (error) {
			// 静默处理错误
		}

		if (orgName) {
			selectedOrgName.value = orgName;
		} else {
			// 如果从组件获取失败，则通过API获取
			await getOrgNameFromApi(orgId);
		}
	} else {
		// 清空组织名称
		selectedOrgName.value = '';
	}
};

const getUserName = (userId: string | number) => {
	const user = allUsers.value.find((u) => u.Value === userId);
	return user?.Text || user?.Name || '未知用户';
};

const getUserCode = (userId: string | number) => {
	const user = allUsers.value.find((u) => u.Value === userId);
	return user?.Code || user?.StaffNo || user?.ITCode || '';
};

// 用户信息显示函数
const getUserInitial = (user: any) => {
	const name = user.Text || user.Name || '未';
	return name.charAt(0).toUpperCase();
};

const getUserDisplayName = (user: any) => {
	return user.Text || user.Name || '未知用户';
};

const getUserDisplayCode = (user: any) => {
	return user.Code || user.StaffNo || user.ITCode || '无';
};

const getUserDisplayDept = (user: any) => {
	return user.DeptName || user.GroupName || user.Department || '无';
};

// 处理头像加载失败
const handleAvatarError = (userId: string | number) => {
	avatarErrors.value[userId] = true;
};

const getJobPositionName = (jobPositionId: string | number | null) => {
	if (!jobPositionId) return '';

	// 优先使用存储的名称（使用==而不是===，避免类型问题）
	if (selectedJobPositionName.value && selectedJobPositionId.value == jobPositionId) {
		return selectedJobPositionName.value;
	}
	// 后备方案：从数据中查找
	const jobPosition = allJobPositions.value.find((j) => j.Value == jobPositionId || j.value == jobPositionId);
	return jobPosition?.Text || jobPosition?.text || jobPosition?.label || '未知岗位';
};

const getDeptName = (deptId: string | number | null) => {
	if (!deptId) return '';

	// 优先使用存储的名称（使用==而不是===，避免类型问题）
	if (selectedDeptName.value && selectedDeptId.value == deptId) {
		return selectedDeptName.value;
	}
	// 后备方案：从数据中查找
	const findDeptInTree = (depts: any[], targetId: string | number): string | null => {
		for (const dept of depts) {
			if (dept.Value == targetId || dept.value == targetId) {
				return dept.Text || dept.text || dept.label;
			}
			if (dept.children && dept.children.length > 0) {
				const found = findDeptInTree(dept.children, targetId);
				if (found) return found;
			}
		}
		return null;
	};

	const deptName = findDeptInTree(allDepts.value, deptId);
	return deptName || '未知部门';
};

const nextStep = () => {
	if (canProceedToNextStep.value) {
		currentStep.value++;
	}
};

const previousStep = () => {
	if (currentStep.value > 0) {
		currentStep.value--;
	}
};

// 取消对话框
const handleCancel = () => {
	emit('closeDialog');
};

const resetDialog = () => {
	currentStep.value = 0;
	selectedUsers.value = []; // 先清空，等数据加载完成后再设置
	selectedOrgId.value = null;
	selectedOrgName.value = '';
	selectedDeptId.value = null;
	selectedDeptName.value = '';
	selectedJobPositionId.value = null;
	selectedJobPositionName.value = '';
	replaceCurrentJob.value = true;
	isProcessing.value = false;
	processProgress.value = 0;
	processedResults.value = [];
	avatarErrors.value = {}; // 清空头像错误状态
};

const handleConfirmAssignment = async () => {
	try {
		const jobPositionText = selectedJobPositionId.value ? `岗位 "${displayJobPositionName.value || '未选择'}"` : '部门';
		await ElMessageBox.confirm(`确定要为 ${selectedUsers.value.length} 名员工分配${jobPositionText}吗？`, '确认操作', {
			type: 'warning',
			confirmButtonText: '确定分配',
			cancelButtonText: '取消',
		});

		isProcessing.value = true;
		processProgress.value = 0;
		processMessage.value = '开始批量分配岗位...';

		// 构建请求数据
		const assignmentData = {
			Ids: selectedUsers.value, // 选取的人员ID数组
			OrgId: String(selectedOrgId.value), // 选取的公司ID
			GroupId: String(selectedDeptId.value), // 选取的部门ID
			JobPositionId: selectedJobPositionId.value ? String(selectedJobPositionId.value) : '', // 选取的岗位ID，可选
		};

		const totalUsers = selectedUsers.value.length;
		processedResults.value = [];

		try {
			// 调用实际的批量分配API
			processMessage.value = `正在批量分配岗位给 ${totalUsers} 名员工...`;
			processProgress.value = 50; // 进行中

			const batchApi = batchOperationsApi();
			await batchApi.batchJobAssignmentRequestBillEntry(assignmentData).then((res) => {
				if (res.Code === 200) {
					ElMessage.success(res.Message);
					processProgress.value = 100; // 完成进度
					processStatus.value = 'success';
					processMessage.value = '批量分配完成！';

					// 触发刷新明细列表
					emit('refresh');

					// 分配成功后关闭弹窗
					setTimeout(() => {
						emit('closeDialog');
					}, 1500); // 1.5秒后关闭，给用户时间看到成功消息
				} else {
					ElMessage.error(res.Message);
					processStatus.value = 'exception';
					processMessage.value = '分配失败：' + res.Message;
				}
			});
		} catch (error: any) {
			ElMessage.error('网络请求失败：' + (error.message || '未知错误'));
			processStatus.value = 'exception';
			processMessage.value = '分配失败：网络错误';
		}
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error('批量分配失败');
		}
	} finally {
		isProcessing.value = false;
	}
};

// 监听选择的部门变化，重新加载对应的岗位
watch(
	selectedDeptId,
	(newDeptId, oldDeptId) => {
		if (newDeptId && currentStep.value === 1) {
			// 修复：应该在步骤1（选择岗位）时加载

			loadJobPositions(newDeptId);
		}
	},
	{ immediate: false }
);

// 监听组织ID变化，更新组织名称
watch(selectedOrgId, async (newOrgId, oldOrgId) => {
	if (newOrgId !== oldOrgId && newOrgId) {
		// 只更新组织名称，不清空其他字段
		await getOrgNameFromApi(newOrgId);
	}
});

// 监听步骤变化，实现懒加载
watch(currentStep, async (newStep) => {
	if (newStep === 1) {
		// 进入第二步时才加载部门数据
		await loadDepts();
	}
});

// 组件挂载时加载数据
onMounted(async () => {
	// 只加载必须的用户数据，其他数据懒加载
	await loadUsers();

	// 如果有传入的用户ID，设置为选中状态
	if (props.wtmdata?.selectedUserIds && props.wtmdata.selectedUserIds.length > 0) {
		selectedUsers.value = [...props.wtmdata.selectedUserIds];
	}

	// 预填充组织和部门信息（如果有提供）
	if (props.wtmdata?.orgId) {
		selectedOrgId.value = props.wtmdata.orgId;
		// 触发组织变化处理，自动加载组织名称
		handleOrgChange(props.wtmdata.orgId);
	}

	// 如果有部门ID，在组织设置完成后设置部门
	if (props.wtmdata?.groupId && props.wtmdata?.orgId) {
		nextTick(() => {
			selectedDeptId.value = props.wtmdata?.groupId || null;
			// 触发部门变化处理
			handleDeptChange(props.wtmdata?.groupId || null);
		});
	}
});
</script>

<style scoped>
.batch-job-assignment-dialog {
	.mb15 {
		margin-bottom: 15px;
	}

	.mb20 {
		margin-bottom: 20px;
	}

	.mr10 {
		margin-right: 10px;
	}

	.dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15px;
		padding-bottom: 12px;
		border-bottom: 1px solid var(--el-border-color-light);

		.header-actions {
			display: flex;
			align-items: center;
			gap: 8px;
		}
	}

	.step-content {
		min-height: 360px;
		padding: 15px 0;
		max-height: calc(100vh - 280px);
		overflow-y: auto;
	}

	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 200px;
		color: var(--el-text-color-regular);
	}

	.step-panel {
		.panel-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;
			padding-bottom: 10px;
			border-bottom: 1px solid var(--el-border-color-light);

			h4 {
				margin: 0;
				color: var(--el-text-color-primary);
			}

			.header-actions {
				display: flex;
				align-items: center;
				gap: 10px;
			}

			.selected-count {
				color: var(--el-color-primary);
				font-weight: bold;
			}

			.selected-users-summary {
				color: var(--el-color-success);
				font-weight: bold;
			}
		}
	}

	.user-selection-area {
		.user-grid {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
			gap: 10px;
			padding: 5px;
		}

		.user-item {
			display: flex;
			align-items: center;
			padding: 10px;
			border: 1px solid var(--el-border-color-light);
			border-radius: 6px;
			cursor: pointer;
			transition: all 0.3s;
			position: relative;
			background-color: var(--el-bg-color-page);

			&:hover {
				border-color: var(--el-color-primary);
				background-color: var(--el-color-primary-light-9);
			}

			&.selected {
				border-color: var(--el-color-success);
				background-color: var(--el-color-success-light-9);
			}

			.user-info {
				flex: 1;
				margin-left: 8px;

				.user-name {
					font-weight: 600;
					color: var(--el-text-color-primary);
					margin-bottom: 2px;
					font-size: 13px;
				}

				.user-detail {
					font-size: 11px;
					color: var(--el-text-color-regular);
					margin-bottom: 1px;
				}

				.user-dept {
					font-size: 10px;
					color: var(--el-text-color-placeholder);
				}
			}

			.selected-icon {
				color: var(--el-color-success);
				font-size: 20px;
			}

			.default-avatar {
				background: linear-gradient(45deg, var(--el-color-primary), var(--el-color-success));
				color: var(--el-color-white);
				font-weight: bold;
			}

			.user-avatar-wrapper {
				position: relative;
			}

			.user-avatar {
				.avatar-loading {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 100%;
					height: 100%;
					background-color: var(--el-fill-color-light);

					.loading-icon {
						color: var(--el-color-primary);
						animation: rotate 2s linear infinite;
					}
				}
			}

			@keyframes rotate {
				from {
					transform: rotate(0deg);
				}
				to {
					transform: rotate(360deg);
				}
			}
		}
	}

	.job-selection-area {
		.assignment-options {
			background: var(--el-fill-color-light);
			padding: 20px;
			border-radius: 8px;

			h5 {
				margin-top: 0;
				margin-bottom: 15px;
				color: var(--el-text-color-primary);
			}

			.el-checkbox {
				display: block;
				margin-bottom: 10px;
			}

			.option-note {
				margin-top: 15px;
				padding: 10px;
				background: var(--el-bg-color);
				border-left: 4px solid var(--el-color-warning);
				border-radius: 4px;
			}
		}

		.assignment-preview {
			margin-top: 20px;

			h5 {
				margin-bottom: 10px;
				color: var(--el-text-color-primary);
			}

			.preview-card {
				.preview-info {
					.el-row {
						margin-bottom: 10px;
					}

					.preview-item {
						padding: 8px 0;

						.preview-label {
							font-size: 13px;
							color: var(--el-text-color-regular);
							margin-bottom: 5px;
						}

						.preview-value {
							font-size: 14px;
							color: var(--el-text-color-primary);
							font-weight: 500;
						}

						&.highlight {
							background: linear-gradient(45deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
							border-radius: 6px;
							padding: 12px;
							text-align: center;

							.preview-label {
								color: var(--el-color-primary);
								font-weight: 500;
							}

							.preview-value {
								color: var(--el-color-primary);
								font-weight: bold;
								font-size: 16px;
							}
						}
					}
				}
			}
		}
	}

	.confirmation-area {
		.confirmation-detail {
			.detail-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 8px 0;
				border-bottom: 1px solid var(--el-border-color-light);

				&:last-child {
					border-bottom: none;
				}

				.detail-label {
					font-size: 13px;
					color: var(--el-text-color-regular);
					min-width: 80px;
				}

				.detail-value {
					font-size: 14px;
					color: var(--el-text-color-primary);
					font-weight: 500;
					text-align: right;
					flex: 1;
					margin-left: 10px;
				}

				&.highlight {
					background: linear-gradient(45deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
					border-radius: 6px;
					padding: 12px;
					margin: 8px 0;
					border: none;

					.detail-label {
						color: var(--el-color-primary);
						font-weight: 500;
					}

					.detail-value {
						color: var(--el-color-primary);
						font-weight: bold;
						font-size: 16px;
					}
				}
			}
		}

		.selected-users-list {
			.user-list-item {
				display: flex;
				align-items: center;
				padding: 8px 0;
				border-bottom: 1px solid var(--el-border-color-light);

				&:last-child {
					border-bottom: none;
				}

				.user-code {
					margin-left: auto;
					color: var(--el-text-color-regular);
					font-size: 12px;
				}
			}
		}

		.processing-area {
			margin-top: 20px;
			padding: 15px;
			background: var(--el-fill-color-light);
			border-radius: 6px;

			.processing-info {
				text-align: center;

				.results-summary {
					margin-top: 10px;

					.success-count {
						color: var(--el-color-success);
						margin-right: 20px;
					}

					.error-count {
						color: var(--el-color-danger);
					}
				}
			}
		}
	}
}

/* ==================== 暗黑模式适配 ==================== */
[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item,
.dark .batch-job-assignment-dialog .user-selection-area .user-item {
	background-color: var(--next-color-primary, #303030) !important;
	border-color: var(--next-border-color, #424242) !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item:hover,
.dark .batch-job-assignment-dialog .user-selection-area .user-item:hover {
	background-color: var(--next-color-hover, #3c3c3c) !important;
	border-color: #409eff !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item.selected,
.dark .batch-job-assignment-dialog .user-selection-area .user-item.selected {
	background-color: var(--next-color-hover, #3c3c3c) !important;
	border-color: #67c23a !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-name,
.dark .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-name {
	color: var(--next-color-bar, #dadada) !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-detail,
.dark .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-detail {
	color: var(--next-text-color-regular, #9b9da1) !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-dept,
.dark .batch-job-assignment-dialog .user-selection-area .user-item .user-info .user-dept {
	color: var(--next-text-color-placeholder, #7a7a7a) !important;
}

[data-theme='dark'] .batch-job-assignment-dialog .user-selection-area .user-item .default-avatar,
.dark .batch-job-assignment-dialog .user-selection-area .user-item .default-avatar {
	color: var(--next-color-white, #ffffff) !important;
}

/* ==================== 响应式布局 ==================== */

/* 平板屏幕 */
@media (max-width: 1024px) {
	.batch-job-assignment-dialog {
		.step-content {
			max-height: calc(100vh - 320px);
		}

		.user-selection-area .user-grid {
			grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
			gap: 8px;
		}

		.dialog-header {
			flex-direction: column;
			gap: 10px;
			align-items: stretch;

			.header-actions {
				justify-content: center;
			}
		}
	}
}

/* 手机屏幕 */
@media (max-width: 768px) {
	.batch-job-assignment-dialog {
		.step-content {
			max-height: calc(100vh - 350px);
			padding: 10px 0;
		}

		.dialog-header {
			margin-bottom: 10px;
			padding-bottom: 8px;

			.header-actions {
				gap: 6px;
			}
		}

		.user-selection-area {
			.user-grid {
				grid-template-columns: 1fr;
				gap: 6px;
				padding: 2px;
			}

			.user-item {
				padding: 8px;

				.user-info {
					margin-left: 6px;

					.user-name {
						font-size: 12px;
					}

					.user-detail {
						font-size: 10px;
					}

					.user-dept {
						font-size: 9px;
					}
				}
			}
		}

		.job-selection-area .el-row {
			--el-row-gutter: 10px;
		}

		.confirmation-area {
			.el-row {
				--el-row-gutter: 10px;
			}

			.el-col:first-child {
				margin-bottom: 15px;
			}
		}

		.panel-header {
			flex-direction: column;
			align-items: stretch;
			gap: 8px;

			.header-actions {
				justify-content: center;
			}
		}
	}
}

/* 小手机屏幕 */
@media (max-width: 480px) {
	.batch-job-assignment-dialog {
		.step-content {
			max-height: calc(100vh - 380px);
		}

		.dialog-header .header-actions {
			flex-direction: column;
			gap: 4px;

			.el-button {
				width: 100%;
			}
		}

		.user-selection-area .user-list .el-scrollbar {
			max-height: 250px;
		}

		.confirmation-area .el-col {
			width: 100%;
			margin-bottom: 10px;
		}

		.panel-header h4 {
			font-size: 16px;
		}
	}
}
</style>
